import React, { useState, useRef, useMemo, useEffect } from 'react'
import { Form, Button } from 'antd'
import { TextWidget } from '@inbiz/react';
import { RenderForm } from '@inbiz/render';
import DocumentAdvancedSearch from './DocumentAdvancedSearch'
import { InterfaceProps } from '../../AdvancedSearch/controlTypeFormItem';
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useJumpResult } from '../../../../../store/hooks/useJumpResult';
import { useSearchUIDispatch } from '../../../../../store/hooks/useSearchUIDispatch';
import { useInbiz } from '../../../../../store/hooks/useInbiz'
import { getFiletypes } from '../../../service'
import { formatTypes } from './utils'
import { getPageSearchData, getDmsSearchData, getsourceUserString, getfileextnameString, gettimeRangeString } from './utils'
import './index.less'

export default function SmallPanelAdvancedSearch(props) {
  const [fileTypeParams, $fileTypeParams] = useState<{ [key: string]: string }[]>([])
  const pageloading = useRef(false);
  const ref = useRef<InterfaceProps & { page: typeof inbiz; }>();
  const metaRef = useRef()
  const [form] = Form.useForm()
  const { selectShowTab } = useSearchUIState()
  const updateUIState = useSearchUIDispatch();
  const onJumpResult = useJumpResult();
  const inbiz = useInbiz()
  const sdk = inbiz?.getGlobalSDK?.() || inbiz?.getSDK?.();


  const getfiletypes = () => {
    getFiletypes().then(res => {
      if (res.result && res.result.length > 0) {
        const types = res.result.map(item => {
          return {
            ...item,
            label: item.FileExtNameTxt,
            value: formatTypes(item)
          }
        })
        $fileTypeParams(types)
      }
    })
  }

  useEffect(() => {
    getfiletypes()
  }, [])
  const onFinish = () => {
    const data = {
      data: {
        SearchWhere: '',
        rawSearchWhere: {},
      },
      dmsType: 'file',
    } as {
      data: {
        SearchWhere: string;
        rawSearchWhere: object;
        inbiz?: any
        Mark?: string,
      };
      dmsType: 'file' | 'folder';
      metaData: any,
      parentFolderLevel?: number,
      parentFolderPath?: string,
      parentTopFolderId?: string,
      parentFolderid: string,
    };
    const values = form.getFieldsValue()

    let parentFolderLevel = null, parentFolderPath = '', parentTopFolderId = '', parentFolderid = ''
    if ((values.filepath && values.filepath.value) || (values.folderpath && values.folderpath.value)) {
      parentFolderLevel = values.filepath?.folderLevel || values.folderpath?.folderLevel
      parentFolderPath = values.filepath?.folderPath || values.folderpath?.folderPath
      parentTopFolderId = values.filepath?.topFolderId || values.folderpath?.topFolderId
      parentFolderid = values.filepath?.value?.[0].folderid || values.folderpath?.value?.[0].folderid
    }

    // 单独处理文件类型
    const {
      fileextname,

      filecreatetime,
      filemodifyoperator,
      filemodifytime,
      filecreateoperator,

      foldermodifytime,
      foldermodifyoperator,
      foldercreateoperator,
      foldercreatetime,
    } = values

    let metaData = Object.values(values).filter(item => {
      if (item?.value && Array.isArray(item.value)) {
        return item && item.value && item.value.length > 0
      }
      return item && item.value
    })
    if (selectShowTab?.associateAdvancedSearchPage) {
      const inbizPage = ref.current?.page;
      const rawSearchWhere = ref.current?.page?.getValue?.() || {};

      data.data = {
        SearchWhere: getPageSearchData(rawSearchWhere),
        rawSearchWhere,
        inbiz: inbizPage,
        Mark: '',
      }
    } else {
      let searchStr = ''
      const otherdata = [{
        key: 'fileextname',
        value: fileextname,
        label: 'SearchEngine.fileType',
        controlType: 'edoc2Selectbox',
        options: fileTypeParams,
        mode: 'singleSelectbox',
      }]
      if (selectShowTab?.isFile) {
        if (filecreateoperator && filecreateoperator.length > 0) {
          const sourceUserString = getsourceUserString(filecreateoperator, 'filecreateoperator')
          searchStr += sourceUserString
        }
        if (filecreatetime && filecreatetime.length > 0) {
          const timeRangeString = gettimeRangeString(filecreatetime, 'filecreatetime')
          searchStr += timeRangeString
        }
        if (filemodifyoperator && filemodifyoperator.length > 0) {
          const sourceUserString = getsourceUserString(filemodifyoperator, 'filemodifyoperator')
          searchStr += sourceUserString
        }
        if (filemodifytime && filemodifytime.length > 0) {
          const timeRangeString = gettimeRangeString(filemodifytime, 'filemodifytime')
          searchStr += timeRangeString
        }
        otherdata.push(...[{
          key: 'filecreatetime',
          value: filecreatetime,
          controlType: 'edoc2Date',
          label: 'SearchEngine.creationTime',
          options: [],
          mode: '',
        }, {
          key: 'filecreateoperator',
          value: filecreateoperator,
          controlType: 'edoc2SelectMember',
          label: 'SearchEngine.creator',
          options: [],
          mode: '',
        }, {
          key: 'filemodifyoperator',
          value: filemodifyoperator,
          controlType: 'edoc2SelectMember',
          label: 'SearchEngine.modifiedBy',
          options: [],
          mode: '',
        }, {
          key: 'filemodifytime',
          value: filemodifytime,
          controlType: 'edoc2Date',
          label: 'SearchEngine.modifiedOn',
          options: [],
          mode: '',
        }])
      } else if (selectShowTab?.isFolder) {
        if (foldercreateoperator && foldercreateoperator.length > 0) {
          const sourceUserString = getsourceUserString(foldercreateoperator, 'foldercreateoperator')
          searchStr += sourceUserString
        }
        if (foldercreatetime && foldercreatetime.length > 0) {
          const timeRangeString = gettimeRangeString(foldercreatetime, 'foldercreatetime')
          searchStr += timeRangeString
        }
        if (foldermodifyoperator && foldermodifyoperator.length > 0) {
          const sourceUserString = getsourceUserString(foldermodifyoperator, 'foldermodifyoperator')
          searchStr += sourceUserString
        }
        if (foldermodifytime && foldermodifytime.length > 0) {
          const timeRangeString = gettimeRangeString(foldermodifytime, 'foldermodifytime')
          searchStr += timeRangeString
        }
        otherdata.push(...[{
          key: 'foldercreatetime',
          value: foldercreatetime,
          controlType: 'edoc2Date',
          label: 'SearchEngine.creationTime',
          options: [],
          mode: '',
        }, {
          key: 'foldercreateoperator',
          value: foldercreateoperator,
          controlType: 'edoc2SelectMember',
          label: 'SearchEngine.creator',
          options: [],
          mode: '',
        }, {
          key: 'foldermodifyoperator',
          value: foldermodifyoperator,
          controlType: 'edoc2SelectMember',
          label: 'SearchEngine.modifiedBy',
          options: [],
          mode: '',
        }, {
          key: 'foldermodifytime',
          value: foldermodifytime,
          controlType: 'edoc2Date',
          label: 'SearchEngine.modifiedOn',
          options: [],
          mode: '',
        }])
      }

      if (fileextname) {
        const fileextnameString = getfileextnameString(fileextname, true)
        searchStr += fileextnameString
      }

      if (metaData.length > 0) {
        searchStr += ` AND ${getDmsSearchData(metaData)}`
      }

      data.data.SearchWhere = searchStr.slice(5);
      data.parentFolderLevel = parentFolderLevel
      data.parentFolderPath = parentFolderPath
      data.parentTopFolderId = parentTopFolderId
      data.parentFolderid = parentFolderid
      if (selectShowTab?.isFile || selectShowTab?.isFolder) {
        data.dmsType = selectShowTab?.isFile ? 'file' : 'folder'
        data.metaData = {
          [data.dmsType]: [...metaData, ...otherdata]
        }
      }
    }
    onJumpResult(data);
    updateUIState({
      showSearchResultPanel: false,
    })
  }

  const renderFormItem = useMemo(() => {
    // if (inbiz.browser.designer) {
    //   return null;
    // }
    if (selectShowTab?.associateAdvancedSearchPage) {
      const id = selectShowTab.associateAdvancedSearchPage.split(',')[0];
      // 渲染远程加载组件
      return (
        <RenderForm
          type="page"
          id={id}
          globalSDK={sdk}
          ref={ref}
          onInit={() => {
            pageloading.current = true;
          }}
        />
      );
    }
    return null;
  }, [selectShowTab?.associateAdvancedSearchPage]);
  const resetValue = () => {
    if (selectShowTab?.associateAdvancedSearchPage) {
      ref.current?.page?.reset?.();
    } else {
      form.resetFields()
      metaRef.current?.resetMetaFields()
    }
  }
  return (
    <div className='advancedSearch'>
      {selectShowTab?.associateAdvancedSearchPage ?
        renderFormItem :
        <DocumentAdvancedSearch form={form} inbiz={inbiz} ref={metaRef} fileTypeParams={fileTypeParams} />
      }
      <div className='operationButtons'>
        <Button type="primary" htmlType="submit" onClick={onFinish}>
          <TextWidget>SearchEngine.search</TextWidget>
        </Button>
        <Button style={{ marginRight: 15 }} onClick={resetValue}>
          <TextWidget>SearchEngine.resetting</TextWidget>
        </Button>
      </div>
    </div>
  )
}
